package com.cms.authority.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.cms.common.kit.Constant;
import com.cms.common.kit.RequestKit;
import com.cms.common.kit.ResponseKit;
import com.cms.common.kit.StrKit;
import com.cms.common.kit.URLKit;
import com.cms.common.util.pass.SystemDecoder;
import com.cms.model.Res;

/**
 * 权限验证拦截器
 * 
 * @author life
 * 
 */
public class AuthorityInteceptor implements HandlerInterceptor {

	private final static Logger logger = Logger.getLogger(AuthorityInteceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 获取URL
		String requestUrl = request.getRequestURI();
		if(!URLKit.checkUrl(requestUrl))return true;
		String realPath=requestUrl.substring(1, requestUrl.length());
		realPath=realPath.substring(realPath.indexOf("/")+1, realPath.length());
		//logger.info("权限拦截请求==>" + request.getRequestURI());
		// 判断是否登录界面或者请求。判断此url是否需要过滤。
		@SuppressWarnings("unchecked")
		List<Res> allRes=Res.dao.findAllRes();
		if(!isNeedCheck(allRes,realPath))return true;
		//取出该用户的权限
		String admin_id = WebUtils.getCookie(request, Constant.CURRENT_ADMIN_COOKIE_INFO).getValue();
		admin_id=SystemDecoder._Decrypt(admin_id);
		List<Res> admin_res_list=Res.dao.findByAdminId(admin_id);
		//检查用户是否有该权限
		if(!hasPremission(admin_res_list,realPath)){
			//如果没有权限，判断是ajax访问还是普通访问
			if (RequestKit.isAjax(request)) {
				response.setCharacterEncoding("utf8");
				response.getWriter().write(ResponseKit.responseError("sorry,you don't have the premission!"));
			}else{
				response.setCharacterEncoding("utf8");
				response.getWriter().write("sorry,you don't have the premission!");
			}
			return false;//返回
		}
		return true;
	}

	private boolean hasPremission(List<Res> admin_res_list, String requestUrl) {
		//获取URL
		boolean hasPermission=false;
		for (Res res : admin_res_list) {
			if(StrKit.isBlank(res.getStr("url")))continue;
			if(res.getStr("url").contains(requestUrl)){
				hasPermission=true;break;
			}
		}
		return hasPermission;
	}


	private boolean isNeedCheck(List<Res> allRes, String requestUrl) {
		boolean need=false;
		for (Res res : allRes) {
			if(StrKit.isBlank(res.getStr("url")))continue;
			if(res.getStr("url").contains(requestUrl)){
				need=true;break;
			}
		}
		return need;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
